package web.servlet.datasource.student;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * @Author: 18148
 * @Date: 2020-05-28 18:53:29
 */
public class StudentDaoDB implements StudentDao {
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    String sql = " ";

    @Override
    public int insert(Student student) {
        Student student1 = selectByName(student.getName());
        if (student1 == null) {
            sql = "insert into student(name,sex,age)values(?,?,?)";
            int i = template.update(sql, student.getName(), student.getSex(), student.getAge());
            return i;
        } else {
            return -1;
        }
    }

    @Override
    public Student selectByName(String name) {
        sql = "select*from student where name=?";
        try {
            Student student = template.queryForObject(sql, new BeanPropertyRowMapper<Student>(Student.class), name);
            return student;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }

    }

    @Override
    public List<Student> selectAll() {
        sql="select *from student";
        try {
            List<Student> list = template.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        return list;
        }catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    @Override
    public int update(int id, Student student) {
        sql="update student set name=?,sex=?,age=? where id=?";
        int i = template.update(sql, student.getName(), student.getSex(), student.getAge(),id);
        return i;
    }

    @Override
    public int delete(int id) {
        sql="delete from student where id=?";
        int i = template.update(sql, id);
        return i;
    }
}
